from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_wtf.csrf import CSRFProtect
from extensions import db
import logging
from datetime import datetime

def create_app():
    app = Flask(__name__)
    
    # 配置
    app.config['SECRET_KEY'] = 'dev'  # 在生产环境中应该使用更安全的密钥
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost/landscape'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    
    # 初始化扩展
    db.init_app(app)
    
    # 初始化 CSRFProtect
    csrf = CSRFProtect()
    csrf.init_app(app)
    
    # 初始化 LoginManager
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    login_manager.login_message = '请先登录'
    login_manager.login_message_category = 'info'
    
    @login_manager.user_loader
    def load_user(user_id):
        from models import User
        return User.query.get(int(user_id))
    
    # 注册蓝图
    from routes import auth, design, community, learning, admin
    app.register_blueprint(auth.auth_bp)
    app.register_blueprint(design.design_bp, url_prefix='/design')
    app.register_blueprint(community.community_bp, url_prefix='/community')
    app.register_blueprint(learning.learning_bp, url_prefix='/learning')
    app.register_blueprint(admin.admin_bp, url_prefix='/admin')
    
    # 添加主页路由
    @app.route('/')
    def index():
        return render_template('index.html')
    
    # 配置日志
    logging.basicConfig(level=logging.INFO)
    app.logger.info('Landscape Design Platform startup')
    
    return app

if __name__ == '__main__':
    app = create_app()
    with app.app_context():
        db.create_all()  # 创建数据库表
    app.run(host='0.0.0.0', port=5001, debug=True) 